
import hashlib
import re
from random import choice
from datetime import datetime,timedelta

from Blog.settings import REGEX_MOBILE,APIKEY
from decorator.functools import check_userToken_timeout,request_method
from utils import Json
from apps.users.models import UserProfile,VerifyCode
from apps.users.serializers import UsersSerializer

from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
from Blog import settings

from utils.yunpian import YunPian

class UserInfoApi(APIView):


    """
    注册
    """
    @csrf_exempt
    @request_method
    def register(request):
        #取出手机号码
        mobile = request.POST.get('mobile')
        #验证码
        code = request.POST.get('code')
        #密码
        password = request.POST.get('password')

        # 验证码在数据库中是否存在，用户从前端post过来的值都会放入initial_data里面，排序(最新一条)。
        verify_records = VerifyCode.objects.filter(mobile=mobile).order_by("-add_time")
        if verify_records:
            # 获取到最新一条
            verify_code = verify_records[0]
            #有效期为5分钟
            five_mintes_ago = datetime.now() - timedelta(hours=0,minutes=5,seconds=0)
            if five_mintes_ago > verify_code.add_time:
                return Json.json_error("验证码过期")

            if verify_code.code != code:
                return Json.json_error("验证码错误")

        else:
            return Json.json_error("验证码错误")

        #保存到数据库
        user = UserProfile(mobile=mobile,password=password)
        user.save()
        return Json.json_response("注册成功")

    """
    登录
    """
    @csrf_exempt
    @request_method
    def login(request):
        # 获取用户
        user = UserProfile.objects.get(pk=request.POST.get('id'))
        if user:
            # 生成Token
            token = hashlib.md5(str(user.id).encode('utf-8') + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")).encode(
                'utf-8')).hexdigest()
            print(token)
            user.token = token
            user.time_out = timedelta(days=7) + datetime.now()
            user.save()
            return Json.json_response("登录成功")
        else:
            return Json.json_error("未找到用户")

    """
    获取用户信息
    """
    @csrf_exempt
    @check_userToken_timeout
    @request_method
    def userInfo(request):
        # 获取用户
        user = UserProfile.objects.get(pk=request.POST.get('id'))
        serializer = UsersSerializer(user)
        re_dict = serializer.data
        re_dict["avatar"] = '%s%s'%(settings.HOST,re_dict["avatar"])
        return Json.JsonResponse(re_dict)


    """
    修改个人信息
    """
    @csrf_exempt
    @check_userToken_timeout
    @request_method
    def updateUsesrInfo(request):
        #serializer = UsersSerializer(data=request.POST)
        data = request.POST
        # 获取用户
        user = UserProfile.objects.get(pk=data['id'])
        if user:
            user.name = user.name if data['name'] == None else data['name']
            user.avatar = user.avatar if request.FILES.get('avatar') == None else request.FILES.get('avatar')
            user.save()
            return Json.json_response("修改成功")
        else:
            return Json.json_error("未找到用户")

    """
    发送验证码
    """
    @csrf_exempt
    @request_method
    def smsCodeWithRegister(request):
        # 获取手机号
        mobile = request.POST.get('mobile')

        # 手机是否注册
        if UserProfile.objects.filter(mobile=mobile).count():
            return Json.json_error("用户已经存在")

        # 验证手机号码是否合法
        if not re.match(REGEX_MOBILE, mobile):
            return Json.json_error("手机号非法")

        # 验证码发送频率
        one_mintes_age = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
        # 添加时间大于一分钟以前，也就是距离现在还不足一分钟
        if VerifyCode.objects.filter(add_time__gt=one_mintes_age, mobile=mobile).count():
            return Json.json_error("距离上一次发送未超过60s")

        # 开始发送验证码
        yun_pian = YunPian(APIKEY)

        code = generate_code()

        sms_status = yun_pian.send_sms(code=code, mobile=mobile)

        if sms_status["code"] != 0:
            return Json.json_error({
                "mobile":sms_status["msg"]}
            )
        else:
            code_record = VerifyCode(code=code, mobile=mobile)
            code_record.save()

            return Json.json_response("发送成功")



"""
   生成四位数字
"""
def generate_code():
    """
    生成四位数字的验证码字符串
    :return:
    """
    seeds = "1234567890"
    random_str = []
    for i in range(4):
        random_str.append(choice(seeds))

    return "".join(random_str)